package com.spring.dynamicdatasource.config;

import com.spring.dynamicdatasource.service.DataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author HouKunLin
 * @date 19-9-10 上午12:17
 */
@WebListener
public class SessionListener implements HttpSessionListener {
    private static Logger logger = LoggerFactory.getLogger(SessionListener.class);
    @Autowired
    private DataSourceService dataSourceService;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        logger.debug("创建会话：{}", se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        logger.debug("会话注销：{}", session.getId());
        dataSourceService.removeDataSource(session);
    }

    @PostConstruct
    public void post() {
        System.out.println("监听器已注入");
    }
}
